// 第一题

// 实现一个pipe函数，传入多个函数（同步或异步），一次执行，最终输出最后一个函数的结果



// 同步代码
const add = x => x + 5;
const multiply = x => x * 5;
const subtraction = x => x - 5;
const division = x => x / 5;

// 思路
// 返回一个函数，且调用这个函数就返回全部函数的处理后的结果
// 先后依次执行管道函数：递归思想  promise.then思想 reduce迭代思想
var pipeFun = function(...fns) {
    return fns.reduce((pre, nxt) => {
        return (x) => {
            let res = pre(x);
            console.log('res:', res);
            return nxt(res);
        }
    });
};

const targetFn = pipeFun(
    add, // 10
    multiply, // 50
    subtraction, // 45
    division // 9
);
targetFn(5); // 9

console.log('pipeFun=》', targetFn(5));








// 异步代码
let syncFn = function(x) {
    return new Promise(resolve => {
        setTimeout(_ => {
            resolve(x)
        }, 500)
    })
}
const add2 = async x => await syncFn(x + 5);
const multiply2 = async x => await syncFn(x * 5);
const subtraction2 = async x => await syncFn(x - 5);
const division2 = async x => await syncFn(x / 5);

let pipeFun2 = (...fns) => {
    return fns.reduce((pre, nxt) => {
        return async (x) => {
            let res = await pre(x);
            return nxt(res)
        }
    })
}

const targetFn2 = pipeFun2(
    add2, // 10
    multiply2, // 50
    subtraction2, // 45
    division2 // 9
);
await targetFn2(5); // 9


console.log('pipeFun=》', await targetFn2(5));